// HTTP 请求工具
import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '../router';
import { handleApiError } from './errorHandler';

const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL || 'http://localhost:3001/api',
  timeout: 10000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');

    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    if (process.env.NODE_ENV === 'development') {
      console.log('发送请求:', {
        url: config.url,
        method: config.method,
        headers: config.headers,
        data: config.data instanceof FormData ? 'FormData' : config.data
      });
    }

    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;

    if (process.env.NODE_ENV === 'development') {
      console.log('收到响应:', {
        url: response.config.url,
        status: response.status,
        data: res
      });
    }

    if (!res.success && res.message) {
      if (process.env.NODE_ENV === 'development') {
        console.error('API返回错误:', res.message);
      }
      ElMessage.error(res.message || '发生错误');

      if (response.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        router.push('/login');
      }

      return Promise.reject(new Error(res.message || '发生错误'));
    }

    return res;
  },
  error => {
    const errorInfo = handleApiError(error, {
      showMessage: true,
      logError: true
    });

    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');

      if (router.currentRoute.value.name !== 'Login') {
        router.push('/login');
      }
    }

    return Promise.reject(error);
  }
);

export default service;